package App.Utility;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class HttpClientUtil
{
  private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
  private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(2000).build();

  public static JSONObject httpPost(String url, JSONObject jsonParam)
  {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    JSONObject jsonResult = null;
    HttpPost httpPost = new HttpPost(url);

    httpPost.setConfig(requestConfig);
    try
    {
      if (null != jsonParam)
      {
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
      }
      CloseableHttpResponse result = httpClient.execute(httpPost);
      if (result.getStatusLine().getStatusCode() == 200)
      {
        String str = "";
        try
        {
          str = EntityUtils.toString(result.getEntity(), "utf-8");

          jsonResult = JSONObject.parseObject(str);
        }
        catch (Exception e)
        {
          logger.error("post请求提交失败:" + url, e);
        }
      }
    }
    catch (IOException e)
    {
      logger.error("post请求提交失败:" + url, e);
    }
    finally
    {
      httpPost.releaseConnection();
    }
    return jsonResult;
  }

  public static JSONObject httpPost(String url, String strParam)
  {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    JSONObject jsonResult = null;
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    try
    {
      if (null != strParam)
      {
        StringEntity entity = new StringEntity(strParam, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
      }
      CloseableHttpResponse result = httpClient.execute(httpPost);
      if (result.getStatusLine().getStatusCode() == 200)
      {
        String str = "";
        try
        {
          str = EntityUtils.toString(result.getEntity(), "utf-8");

          jsonResult = JSONObject.parseObject(str);
        }
        catch (Exception e)
        {
          logger.error("post请求提交失败:" + url, e);
        }
      }
    }
    catch (IOException e)
    {
      logger.error("post请求提交失败:" + url, e);
    }
    finally
    {
      httpPost.releaseConnection();
    }
    return jsonResult;
  }

  public static JSONObject httpGet(String url)
  {
    JSONObject jsonResult = null;
    CloseableHttpClient client = HttpClients.createDefault();

    HttpGet request = new HttpGet(url);
    request.setConfig(requestConfig);
    try
    {
      CloseableHttpResponse response = client.execute(request);
      if (response.getStatusLine().getStatusCode() == 200)
      {
        HttpEntity entity = response.getEntity();
        String strResult = EntityUtils.toString(entity, "utf-8");

        jsonResult = JSONObject.parseObject(strResult);
      }
      else
      {
        logger.error("get请求提交失败:" + url);
      }
    }
    catch (IOException e)
    {
      logger.error("get请求提交失败:" + url, e);
    }
    finally
    {
      request.releaseConnection();
    }
    return jsonResult;
  }

  public static String doPost(String url, Map<String, String> param)
    throws IOException
  {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    String resultString = "";
    try
    {
      if (param != null)
      {
        List<NameValuePair> paramList = new ArrayList();

        Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator();

        while ( iterator.hasNext() ) {
          Map.Entry<String, String> entry = iterator.next();

          paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
//        for (String key : param.keySet()) {
//          paramList.add(new BasicNameValuePair(key, (String)param.get(key)));
//        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
        httpPost.setEntity(entity);
      }
      CloseableHttpResponse response = httpClient.execute(httpPost);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      httpPost.releaseConnection();
    }
    return resultString;
  }

  public static String sendGet(String url, String param)
  {
    StringBuilder result = new StringBuilder();
    BufferedReader in = null;
    try
    {
      String urlNameString = url + "?" + param;
      URL realUrl = new URL(urlNameString);

      URLConnection connection = realUrl.openConnection();

      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection", "Keep-Alive");
      connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");



      connection.connect();

      Map<String, List<String>> map = connection.getHeaderFields();

      Iterator<Map.Entry<String, List<String>>> iterator = map.entrySet().iterator();

      while ( iterator.hasNext() ) {
        Map.Entry<String, List<String>> entry = iterator.next();

        logger.info(entry.getKey() + "--->" +entry.getValue());

      }
      in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result.append(line);
//        result = result + line;
      }

    }
    catch (Exception e)
    {
      System.out.println("发送GET请求出现异常！" + e);
      e.printStackTrace();
    }
    finally
    {
      try
      {
        if (in != null) {
          in.close();
        }
      }
      catch (Exception e2)
      {
        e2.printStackTrace();
      }
    }
    return result.toString();
  }

  public static String sendPost(String url, String param)
  {
    PrintWriter out = null;
    BufferedReader in = null;
    StringBuilder result =new StringBuilder();
    try
    {
      URL realUrl = new URL(url);

      URLConnection conn = realUrl.openConnection();

      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      conn.setRequestProperty("Authorization","Basic ZTExMTczNjliMGEzOWU0MjE4NTA0MmFhOjNhOTUwMDJjNGNmZTg0ODgxNmZjMThkYg==");
      conn.setRequestProperty("Content-Type","application/json");


      conn.setDoOutput(true);
      conn.setDoInput(true);

      out = new PrintWriter(conn.getOutputStream());

      out.print(param);

      out.flush();


      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result.append(line);
      }

    }
    catch (Exception e)
    {
      System.out.println("发送 POST 请求出现异常！" + e);
      e.printStackTrace();
    }
    finally
    {
      try
      {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      }
      catch (IOException ex)
      {
        ex.printStackTrace();
      }
    }
    return result.toString();
  }

  public static void main(String[] args) {
    String url = "https://api.verification.jpush.cn/v1/web/loginTokenVerify";
    JSONObject param = new JSONObject();
    param.put("loginToken","1A2So95Yz8/Bdr1lXRdKvOd1m9+0B3Cfz/GNenpvCqtoKTzw9NI0UVFgWZnvEnRnc7LvEJ9m9DifkMcomavZl3GSRcQM2YHW6rCf8AtnqW3eEy/PKLfDrD1YO8LryqcIEbmd/5fMH3bqA8viTcgh0/b0LZa02cBQiL5ReQIgfC/bU2yjgGBn+1/ejiBpU8H39PXIll2la6dDH1FxdfCntw2Za8WPtGsKvsS5AYo2Xz6Am3Lfki9LMyMugzBVJPeoU2QlvQZKlBcIHcKMqTt8Bxyey+pPkgPnqbkpbpeWnIC35DWjhEf/tVb6vt7on87BmCFNABTXgx2fnQpBze3d4H3KIPhkGC5q5BNbl/dEiWHcrzcjXVfpDG57AJ9arXhPHrvaIbpcdXOxkZxukSI1oJelK+ewAREtovLEgYVJVeQ=");
    String res = null;
      res = sendPost(url,param.toString());
    System.out.println(res);
  }


}
